<template>
  <div>
    <div class="mobile_entry_header">
      <van-nav-bar class="main_header" title="报名" left-text="返回" left-arrow @click-left="goback()">
        <template #right>
          <van-icon v-show="stepList[stepActive].component === 'step-by-official' && currentUserType === 'Personal'" size="18px" name="manager" @click="clickChooseOfficial()" />
          <van-icon v-show="stepList[stepActive].component === 'step-by-official' && currentUserType === 'Delegation'" size="18px" name="manager" @click="clickAddOfficial()" />
          <van-icon v-show="stepList[stepActive].component === 'step-by-athlete' && currentUserType === 'Delegation' && athletePageType !== 'confirm'" size="18px" name="manager" @click="clickAddAthlete()" />
        </template>
      </van-nav-bar>
    </div>

    <div class="mobile_entry_content_wrap">
      <template v-if="UserType && gameInfo">
        <component
          :is="item.component"
          v-for="(item, index) in stepList"
          v-show="stepActive === index"
          :key="index"
          :ref="'enter-' + item.component"
          class="component_wrap"
          :is-show="stepActive === index"
          :user-type="UserType"
          :current-user-type="currentUserType"
          :dict="dict"
          :district="cache.district"
          :game-info="gameInfo"
          :user-info="userInfo"
          :user-team-info="userTeamInfo"
          :official-data="officialData"
          :required-id-data="requiredIdData"
          :attach-official="attachOfficial"
          :game-tenant-id="gameTenantId"
          @onPrevStep="doPrevStep"
          @onNextStep="doNextStep"
          @onChangeCurrentUserType="changeCurrentUserType"
          @onConfirmSign="confirmSign"
          @onGetUserInfo="getUserInfo"
          @onGetUserTeamInfo="getUserTeamInfo"
          @onChangeOfficialData="changeOfficialData"
          @onAddAttachOfficial="addAttachOfficial"
          @reGetUserType="reGetUserType"
          @onChangeAthletePageType="changeAthletePageType"
        />
      </template>
    </div>

    <div v-if="!(UserType && gameInfo)" class="page_loading fixed">
      <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

import {
  api_GET_EventsManagementUserUserType, // 获取当前用户注册类型
  api_GET_EventsManagementCompetitionWithRoute,
  api_GET_EventsManagementRegisterId, // 获取注册信息
  api_GET_EventsManagementDelegationId // 获取团体注册信息
} from '@/extend/api/gameswaggerApi/app';

import StepByType from './components/stepByType';
import StepByInfo from './components/stepByInfo';
import StepByOfficial from './components/stepByOfficial';
import StepByAthlete from './components/stepByAthlete';
import StepBySubmit from './components/stepBySubmit';
import { getToken } from '@/lib/auth';
import { loginOidc } from '@/lib/oidc_fun';

export default {
  components: {
    StepByType,
    StepByInfo,
    StepByOfficial,
    StepByAthlete,
    StepBySubmit
  },
  data() {
    return {
      pageLoading: false, // 关键性Loading,，不可轻易false
      stepActive: 0, // 当前步骤位置
      stepList: [ // 步骤条数据
        {
          title: '确认信息',
          component: 'step-by-info'
        },
        {
          title: '选择教练',
          component: 'step-by-official'
        },
        {
          title: '选手报名',
          component: 'step-by-athlete'
        },
        {
          title: '完成',
          component: 'step-by-submit'
        }
      ],
      dynamicStepList: { // 动态步骤列表数据，此数据中的内容视情况添加进stepList
        stepByType: {
          title: '确认身份',
          component: 'step-by-type'
        }
      },
      currentUserType: '', // 当前用户的选择的报名类型 Personal : 个人，Delegation：团体
      officialData: [], // 官员数据
      userInfo: null, // 用户信息
      userTeamInfo: null, // 团体信息
      gameInfo: null, // 赛事信息
      gameRoute: '', // 赛事路由
      gameTenantId: '', // 赛事tenantId
      gameId: '', // 赛事ID
      requiredIdData: { // 后续步骤需要的ID，此页面不要调用，修改会对后续步骤数据提交有影响，慎重！
        delegationId: '',
        registerId: ''
      },
      attachOfficial: [], // 附加的临时官员
      athletePageType: ''
    };
  },
  computed: {
    ...mapState({
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    'UserType': {
      immediate: true,
      deep: true,
      handler (val) {
        if (val) {
          this.requiredIdData.registerId = val.registerId;
          this.requiredIdData.delegationId = val.delegationId;
          this.getUserInfo();
          this.getUserTeamInfo();
          if (this.stepList.length === 4 && val.userType.code === 'PersonalDelegation') {
            this.stepList.unshift(this.dynamicStepList.stepByType);
          }
          this.checkUserAndUserteamReady();
        }
      }
    },
    currentUserType() {
      // currentUserType 变更后需 changeRequiredIdData
      this.changeRequiredIdData();
    }
  },
  created() {
    // 如果当前页面没有token
    this.tokenInfo = getToken();
    this.tenantId = this.$route.params.id.split('_')[1];
    if (!this.tokenInfo) {
      this.goLogin();
      return;
    }
    const $route = this.$route;
    const _paramsId = $route.params.id;
    this.gameRoute = _paramsId.split('_')[0];
    this.gameTenantId = process.env.VUE_APP_Get_TenantId;
    console.log("🚀 ~ file: index.vue:165 ~ created ~ this.gameTenantId:", this.gameTenantId)

    this.getDict();
    this.getDictByType(['district']);
    this.getGameInfoByGameRoute();
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    goLogin() {
      let tenantId = this.tenantId ? this.tenantId : '';
      tenantId = tenantId + '___' + ENVIR;
      let href = window.location.href;
      href =
        href.indexOf('#') > -1
          ? href.indexOf('?') > -1
            ? href + '&'
            : href + '?'
          : href + '#/?';
      href = href
        .replace(/loginRandom=[0-9]+|loginRandom=/g, '')
        .replace(/&&+/g, '&')
        .replace('?&', '?');
      href = href + 'loginRandom=' + new Date().getTime();
      // 跳转登录
      loginOidc({
        state: window.btoa(href),
        acr_values: tenantId ? window.btoa(tenantId) : ''
      });
    },
    reGetUserType() {
      this.pageLoading = true;
      api_GET_EventsManagementUserUserType()
        .then(res => {
          this.$store.dispatch('user/getSaveCurrentUserType', res);
          this.pageLoading = false;
        });
    },
    // 根据赛事路由获取赛事信息
    getGameInfoByGameRoute() {
      const gameQO = {
        IncludeStatus: true,
        IncludeType: true,
        IncludeApproveStatus: true,
        IncludeLevel: true,
        IncludeSetting: true,
        IncludeReportSetting: true,
        IncludeEntryFields: true
      };
      gameQO.route = this.gameRoute;
      if (this.gameTenantId) {
        gameQO.__tenant = this.gameTenantId;
      }
      api_GET_EventsManagementCompetitionWithRoute(gameQO).then(res => {
        this.gameInfo = res || {};
        this.gameId = this.gameInfo.id;
        this.checkGameCanEntry();
      });
    },
    // 检查赛事是否可以报名
    checkGameCanEntry () {
      // 如果赛事不在报名阶段，则跳转至赛事首页
      const _gameInfo = this.gameInfo;
      const _status = _gameInfo.status;
      // const _gameRoute = this.$route.params.id;
      if (_status.code !== 'EntryStarted') {
        this.$toast({
          message: `赛事不在报名时间内，无法报名！`,
          type: 'fail'
        });
        this.goback();
      } else {
        this.checkUserAndUserteamReady();
      }
    },
    // 获取用户信息
    getUserInfo() {
      // 获取个人注册信息
      if (this.UserType.registerId) {
        const _qo = {
          IncludeDelegation: true
        };
        api_GET_EventsManagementRegisterId(this.UserType.registerId, _qo)
          .then(res => {
            this.userInfo = res;
            console.log('getUserInfo -> userInfo', res);
            if (this.UserType.userType.code === 'Personal') {
              this.requiredIdData.delegationId = res.delegationId;
            }
          })
          .catch(
            error => {
              console.log('getUserInfo -> error: ', error);
              this.$toast({ type: 'fail', message: '获取用户信息失败' });
            }
          );
      } else {
        console.log('UserType中缺失registerId');
      }
    },
    // 获取团体注册信息
    getUserTeamInfo() {
      if (this.UserType.delegationId) {
        api_GET_EventsManagementDelegationId(this.UserType.delegationId)
          .then(res => {
            this.userTeamInfo = res;
            console.log('getUserTeamInfo -> userTeamInfo', res);
          })
          .catch(
            error => {
              console.log('getUserTeamInfo -> error', error);
              this.$toast({ type: 'fail', message: '获取团体信息失败' });
            }
          );
      } else {
        console.log('UserType中缺失delegationId');
      }
    },
    // 确认报名后汇聚信息并提交
    confirmSign (data) {
      console.log('confirmSign -> data', data);
      this.doNextStep();
    },
    // 根据Step0类型选择修改当前类型
    changeCurrentUserType (data) {
      this.currentUserType = data.code;
    },
    changeRequiredIdData() {
      if (this.UserType.userType.code === 'PersonalDelegation' && this.currentUserType === 'Personal') {
        this.requiredIdData.delegationId = this.userInfo ? this.userInfo.delegationId : null;
      }
      if (this.UserType.userType.code === 'PersonalDelegation' && this.currentUserType === 'Delegation') {
        this.requiredIdData.delegationId = this.UserType.delegationId;
      }
    },
    // 从子模块获取官员数据
    changeOfficialData (data) {
      this.officialData = data;
      console.log(this.officialData);
    },
    // 添加附加的裁判教练或其他人员
    addAttachOfficial (data) {
      const _officicalData = this.attachOfficial.find(item => item.id === data.id);
      if (_officicalData) {
        const _tagData = _officicalData.registerTags.find(item => {
          return item.registerTagTypeCode === data.registerTags[0].registerTagTypeCode;
        });
        if (!_tagData) {
          _officicalData.registerTags.push(data.registerTags[0]);
        }
      } else {
        this.attachOfficial.push(data);
      }
    },
    // 用于修改报项，保证信息完整的情况下进行跳转
    checkUserAndUserteamReady() {
      const _gameInfoId = this.gameInfo ? this.gameInfo.id : '';
      const _gameSetting = this.gameInfo ? this.gameInfo.setting : '';
      const _modifyType = this.$route.query.modifyType;

      // 赛事id存在 且 赛事有配置 且 类型为修改
      if (this.UserType && _gameInfoId && _gameSetting && _modifyType) {
        // 修改类型为个人
        if (_modifyType === 'Personal') {
          this.$nextTick(() => {
            this.$refs['enter-step-by-type'][0].chooseConfirmInfo({
              name: '个人报名通道',
              code: 'Personal'
            }, 0);
            this.$refs['enter-step-by-type'][0].clickNextStep();
          });
        }
        //  修改类型为团体
        if (_modifyType === 'Delegation') {
          this.$nextTick(() => {
            this.$refs['enter-step-by-type'][0].chooseConfirmInfo({
              name: '代表队报名通道',
              code: 'Delegation'
            }, 1);
            this.$refs['enter-step-by-type'][0].clickNextStep();
          });
        }
      }
    },
    changeAthletePageType (type) {
      this.athletePageType = type;
    },
    // 执行上一步
    doPrevStep () {
      if (this.stepActive <= 0) {
        return false;
      }
      this.stepActive--;
      return true;
    },
    // 执行下一步
    doNextStep () {
      if (this.stepActive >= this.stepMaxLen) {
        return false;
      }
      this.stepActive++;
      return true;
    },
    // 返回上一页
    goback() {
      this.$router.push({
        name: 'HomeGame'
      });
    },
    // -----
    clickAddOfficial () {
      this.$refs['enter-step-by-official'][0].clickAddOfficial();
    },
    clickChooseOfficial () {
      this.$refs['enter-step-by-official'][0].clickChooseOfficial();
    },
    clickAddAthlete () {
      this.$refs['enter-step-by-athlete'][0].clickAddAthlete();
    }
  }
};
</script>

<style>
.component_wrap {
  padding: 10px;
}
.bottom_btn_position {
  position: fixed;
  /* position: absolute; */
  box-sizing: border-box;
  width: 100%;
  padding: 0 10px 10px;
  bottom: 0;
  left: 0;
  background-color: #fff;
}
</style>

<style lang="scss" scoped>
.mobile_entry_header {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
}
.mobile_entry_content_wrap {
  position: absolute;
  top: 46px;
  bottom: 55px;
  overflow: scroll;
  width: 100%;
}
</style>
